/****************************************************************************
 * 2025.10 XLB-20250122JTG
 ****************************************************************************/

using System;
using System.Collections.Generic;
using QAssetBundle;
using UnityEngine;
using UnityEngine.UI;
using QFramework;
using UnityEngine.U2D;

namespace ProjectSurvivor
{
	public partial class ExpUpgradePanel : UIElement, IController
	{
		private ResLoader mResLoader;
		private void Awake()
		{
			mResLoader = ResLoader.Allocate();
			var iconAtlas = mResLoader.LoadSync<SpriteAtlas>("icon");
			
			var expUpgradeSystem = this.GetSystem<ExpUpgradeSystem>();

			BtnExpUpgradeItemTemplate.Hide();

			foreach (var expUpgradeItem in expUpgradeSystem.Items)
			{
				var itemCache = expUpgradeItem;
				
				BtnExpUpgradeItemTemplate.InstantiateWithParent(UpgradeRoot)
					.Self(self =>
					{
						var selfCache = self;
						selfCache.transform.Find("Icon").GetComponent<Image>().sprite = iconAtlas.GetSprite(itemCache.IconName);
						selfCache.onClick.AddListener(() =>
						{
							Time.timeScale = 1;
							AudioKit.PlaySound(Sfx.ABILITYLEVELUP);
							itemCache.Upgrade();
							this.Hide();
						});

						

						itemCache.Visible.Register(visible =>
						{
							Transform description = selfCache.transform.Find("Description");
							Transform pairName = selfCache.transform.Find("PairName");
							Transform pairIcon = selfCache.transform.Find("PairIcon");
							
							if (visible)
							{
								description.GetComponent<Text>().text = expUpgradeItem.Description;
								
								pairName.Hide();
								pairIcon.Hide();
								
								if(expUpgradeSystem.Pairs.TryGetValue(itemCache.Key, out var pairedName))
								{
									var pairItem = expUpgradeSystem.DictionaryExpUpgradeItems[pairedName];
									if (pairItem.CurrentLevel.Value > 0 && pairItem.CurrentLevel.Value == 0)
									{
										pairName.GetComponent<Text>().text = "配对技能：";
										pairIcon.GetComponent<Image>().sprite = iconAtlas.GetSprite(pairItem.IconName);
										pairName.Show();
										pairIcon.Show();
									}
								}
								selfCache.Show();
							}
							else
							{
								selfCache.Hide();
							}
						}).UnRegisterWhenGameObjectDestroyed(selfCache);
					});
			}
		}

		protected override void OnBeforeDestroy()
		{
			mResLoader.Recycle2Cache();
			mResLoader = null;
		}

		public IArchitecture GetArchitecture()
		{
			return Global.Interface;
		}
	}
}